/**
* @program: src
*
* @description:
*
* @author: Mr.chen
*
* @create: 2022-04-12 10:14
**/
package response
import (
	"do_demo/srv/common/core/logx"
	"do_demo/srv/common/perr"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"google.golang.org/grpc/status"
)


func ResultErrors(c *gin.Context, code,errcode int,errorMsg string ) {
	c.Set(contextErrCode, code)
	resp := Error(errcode,errorMsg)
	c.JSON(200, resp)
}

func ResultSuccess(c *gin.Context,data interface{}, code int) {
	c.Set(contextErrCode, code)
	resp := Success(data)
	c.JSON(200, resp)
}

//http返回
func HttpResult(c *gin.Context, resp interface{}, err error) {
	if err == nil {
		logx.WithContext(c.Request.Context()).Infof("【API-success】url: %s, respon: %s ",c.Request.URL, resp)
		//成功返回
		ResultSuccess(c,resp,OK)
	} else {
		//错误返回
		errcode := perr.SERVER_COMMON_ERROR
		errmsg := "服务器开小差啦，稍后再来试一试"

		causeErr := errors.Cause(err)                // err类型，是否api端用到了 errors.Wrap(perr.NewErrMsg("账号或密码不正确"), "密码匹配出错")
		if e, ok := causeErr.(*perr.CodeError); ok { //自定义错误类型
			//自定义CodeError
			errcode = e.GetErrCode()
			errmsg = e.GetErrMsg()
		} else { // 没有用到处理grpc的错误，rpc error: code = Code(100001) desc = 账号不存在
			if gstatus, ok := status.FromError(causeErr); ok { // grpc err错误,获取返回grpc的状态码跟消息，不存在返回默认的消息码
				grpcCode := int(gstatus.Code())
				if perr.IsCodeErr(grpcCode) { //区分自定义错误跟系统底层、db等错误，底层、db错误不能返回给前端
					errcode = grpcCode
					errmsg = gstatus.Message()
				}
			}
		}
		// 链路追踪
		logx.WithContext(c.Request.Context()).Errorf("【API-ERR】 : %+v ", err)
		// 链路追踪
		ResultErrors(c,RequestErr,errcode, errmsg)
		//httpx.WriteJson(w, http.StatusBadRequest, Error(errcode, errmsg))
	}
}